package com.csdj.t309springboot.controller;
import com.csdj.t309springboot.common.CacheConstant;
import com.csdj.t309springboot.common.WebResult;
import com.csdj.t309springboot.common.WebResultMsgCode;
import com.csdj.t309springboot.entity.IntegralRecord;
import com.csdj.t309springboot.entity.SignInRecord;
import com.csdj.t309springboot.entity.User;
import com.csdj.t309springboot.service.IntegralRecordService;
import com.csdj.t309springboot.service.RedisService;
import com.csdj.t309springboot.service.SignInRecordService;
import com.csdj.t309springboot.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 谭湛宇
 * @since 2022-01-12
 */
@RestController
@RequestMapping("/signInRecord")
public class SignInRecordController extends BaseController{
    private Logger log = LoggerFactory.getLogger("");
    @Resource
    private SignInRecordService signInRecordService;
    @Resource
    private IntegralRecordService integralRecordService;
    @Resource
    private UserService userService;

//    @Resource
//    private RedisService redisService;
    /**
     * 检查是否签到
     * @param request HttpServletRequest request
     * @return
     */
    @GetMapping("/checkSignIn")
    public WebResult checkSignIn(HttpServletRequest request){
        int userId = getUid(request);
        SignInRecord signInRecord = signInRecordService.checkSignIn(userId);
        //计算现在时间距离今天24:00差多少秒数,保存到redis里,剩下的时间是 键的过期过期时间,单位:秒
        //如果键存在, 说明今天签到了,并返回结果


        if(null != signInRecord){
            return new WebResult(WebResultMsgCode.SUCCESS,true).putData("entity",signInRecord);
        }
        return new WebResult(WebResultMsgCode.SUCCESS,false).putData("entity",null);
    }

    /**
     * 签到规则:
     * 1.1天只能 签到一次，
     * 2.当天签后这个按钮不可用
     * 3.签到送积分规则：第一天送一个积分， 第二天送两个积分， 第三天送三个积分依次灰推，直到连续签到15天，
     * 第十六天开始也只是送十五个积分。如果中途中断了签到，则从头开始计算。
     * 这些送积分信息也是不能写死在代码里，需要能够灵活配置。
     * @param request HttpServletRequest对象
     * @return 统一返回 WebResult对象
     */
    @PostMapping("/update")
    public WebResult updateById(HttpServletRequest request){
        int userId = getUid(request);
        log.info("getUserSignInRecord() userId="+userId);
        SignInRecord signInRecord2 = signInRecordService.getSignInRecordByUserId(userId);
        log.info("LocalDate.now()="+LocalDate.now());
        if(null != signInRecord2 && signInRecord2.getSignInDate().equals(LocalDate.now())){//今天已签到
            log.info("已签到");
            return new WebResult(WebResultMsgCode.SUCCESS,true);
        }
        //未签到
        log.info("未签到,执行签到操作");
        //查询用户的id,积分和签到天数
        SignInRecord userInfo = signInRecordService.getSignInRecordByUserId(userId);
        //设置签到实体类的值
        SignInRecord signInRecord = new SignInRecord();
        signInRecord.setId(userInfo.getId());
        signInRecord.setUserId(userId);
        //设置签到日期为今天; LocalDate方法介绍: now() : 从默认时区的系统时钟中获取当前日期。
        signInRecord.setSignInDate(LocalDate.now());
        //查询原来的积分信息
        IntegralRecord integralRecordInfo = integralRecordService.getIntegralRecordInfoByUserId(userId);
        //增加积分记录信息
        IntegralRecord integralRecord = new IntegralRecord();
        integralRecord.setUserId(userId);
        //操作类型
        integralRecord.setIntegralSource("签到");
        //增加用户的积分数量
        User user = userService.getUserInfoById(userId);

        //如果连续签到天数大于15天//签到奖励的积分, 最多奖励 15积分
        if(userInfo.getConsecutiveSignInDays()>CacheConstant.MAX_NUMBER_OF_INTEGRAL){
            //设置连续签到天数 +1自增, 积分等于原积分+签到奖励积分
            signInRecord.setConsecutiveSignInDays(userInfo.getConsecutiveSignInDays()+1);
            signInRecord.setScore(userInfo.getScore()+ CacheConstant.MAX_NUMBER_OF_INTEGRAL);
            integralRecord.setIntegralNumber(CacheConstant.MAX_NUMBER_OF_INTEGRAL);
            integralRecord.setIntegralBalance(integralRecordInfo.getIntegralBalance()+CacheConstant.MAX_NUMBER_OF_INTEGRAL);
            user.setIntegralNumber(user.getIntegralNumber()+CacheConstant.MAX_NUMBER_OF_INTEGRAL);
        }
        //签到记录表//设置连续签到天数 +1自增, 积分等于原积分+签到奖励积分
        signInRecord.setConsecutiveSignInDays(userInfo.getConsecutiveSignInDays()+1);
        signInRecord.setScore(userInfo.getScore()+signInRecord.getConsecutiveSignInDays());
        //积分记录表//奖励与签到天数相同的积分
        integralRecord.setIntegralChange(userInfo.getConsecutiveSignInDays()+CacheConstant.MIN_NUMBER_OF_INTEGRAL);
        //积分余额等于原来的积分余加上改动的积分
        integralRecord.setIntegralBalance(integralRecordInfo.getIntegralBalance()+integralRecord.getIntegralChange());
        //设置用户表的积分余额
        user.setIntegralNumber(user.getIntegralNumber()+signInRecord.getConsecutiveSignInDays());
        user.setSignInNumberOfDays(userInfo.getConsecutiveSignInDays()+1);
        log.info("signInRecord="+signInRecord);
        //修改签到记录信息
        boolean updateById = signInRecordService.updateById(signInRecord);
        boolean updateUserById = userService.updateById(user);
        //新增积分记录
        int insert = integralRecordService.insert(integralRecord);

        log.info("updateById="+updateById+",updateUserById="+updateUserById);
        log.info("insert="+insert);
        if(updateById &&updateUserById && insert>0){
            return new WebResult(WebResultMsgCode.SUCCESS,true);
        }
        return new WebResult(WebResultMsgCode.SUCCESS,false);
    }
    /**
     * 根据用户编号查询签到记录
     * @return
     */
    @GetMapping("/getSignInRecordInfoByUserId")
    public WebResult getUserSignInRecord(HttpServletRequest request){
        int userId = getUid(request);
        log.info("getUserSignInRecord() userId="+userId);
        SignInRecord signInRecord = signInRecordService.getSignInRecordByUserId(userId);
        if(null != signInRecord){
            return new WebResult(WebResultMsgCode.SUCCESS).putData("entity",signInRecord);
        }
        return new WebResult(WebResultMsgCode.FAIL).putData("error","error操作失败");
    }
}
